package org.example.school.business;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.school.common.Result;
import org.example.school.entity.Assignments;
import org.example.school.entity.AssignmentSubmissions;
import org.example.school.entity.Students;
import org.example.school.entity.Subjects;
import org.example.school.model.dto.AssignmentSubmissionDTO;
import org.example.school.model.dto.StudentAssignmentDTO;
import org.example.school.service.IAssignmentSubmissionsService;
import org.example.school.service.IAssignmentsService;
import org.example.school.service.IStudentsService;
import org.example.school.service.ISubjectsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class StudentHomeworkInfo extends CommonInfo {

    @Autowired
    private IAssignmentsService assignmentsService;

    @Autowired
    private IAssignmentSubmissionsService assignmentSubmissionsService;

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private ISubjectsService subjectsService;

    /**
     * 获取学生作业列表
     *
     * @return 作业列表
     */
    public Result<List<StudentAssignmentDTO>> getHomeworkList(String status) {
        try {
            // 获取当前学生信息
            Students student = this.getUserByStudent().getData();
            if (student == null) {
                return Result.error("学生信息不存在");
            }

            // 查询该班级的作业列表
            QueryWrapper<Assignments> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("class_id", student.getClassId());
            queryWrapper.orderByDesc("created_at");

            List<Assignments> assignmentsList = assignmentsService.list(queryWrapper);

            // 转换为StudentAssignmentDTO
            List<StudentAssignmentDTO> studentAssignments = assignmentsList.stream().map(assignment -> {
                StudentAssignmentDTO dto = new StudentAssignmentDTO();
                BeanUtils.copyProperties(assignment, dto);

                // 获取学科名称
                Subjects subject = subjectsService.getById(assignment.getSubjectId());
                if (subject != null) {
                    dto.setSubjectName(subject.getName());
                }

                // 获取提交状态
                QueryWrapper<AssignmentSubmissions> submissionQuery = new QueryWrapper<>();
                submissionQuery.eq("assignment_id", assignment.getId());
                submissionQuery.eq("student_id", student.getId());
                AssignmentSubmissions submission = assignmentSubmissionsService.getOne(submissionQuery);

                if (submission != null) {
                    dto.setSubmissionStatus(submission.getStatus());
                    dto.setFeedback(submission.getFeedback());
                    dto.setGrade(submission.getGrade());
                } else {
                    // 如果没有提交记录，则状态为1(未完成)
                    dto.setSubmissionStatus(1);
                }
                return dto;
            }).collect(Collectors.toList());
            if (StringUtils.isEmpty(status)) {
                return Result.success(studentAssignments);
            }
            List<StudentAssignmentDTO> filteredAssignments = studentAssignments.stream()
                    .filter(assignment -> assignment.getSubmissionStatus().equals(Integer.parseInt(status)))
                    .collect(Collectors.toList());
            return Result.success(filteredAssignments);
        } catch (Exception e) {
            return Result.error("查询作业列表异常: " + e.getMessage());
        }
    }

    /**
     * 提交作业
     *
     * @param submissionDTO 作业提交信息
     * @return 提交结果
     */
    public Result<String> submitHomework(AssignmentSubmissionDTO submissionDTO) {
        try {
            // 获取当前学生信息
            Students student = this.getUserByStudent().getData();
            if (student == null) {
                return Result.error("学生信息不存在");
            }

            // 检查作业是否存在
            Assignments assignment = assignmentsService.getById(submissionDTO.getAssignmentId());
            if (assignment == null) {
                return Result.error("作业不存在");
            }
            //截止时间
            if (!assignment.getDueDate().isBefore(LocalDateTime.now())) {
                return Result.error("作业已截止");
            }

            // 检查是否已经提交过该作业
            QueryWrapper<AssignmentSubmissions> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("assignment_id", submissionDTO.getAssignmentId());
            queryWrapper.eq("student_id", student.getId());
            AssignmentSubmissions existingSubmission = assignmentSubmissionsService.getOne(queryWrapper);

            if (existingSubmission != null) {
                // 如果已经提交过，则更新提交内容
                existingSubmission.setContent(submissionDTO.getContent());
                existingSubmission.setAttachmentUrl(submissionDTO.getAttachmentUrl());
                existingSubmission.setSubmittedAt(LocalDateTime.now());
                // 状态设置为2(已提交)
                existingSubmission.setStatus(2);

                boolean updated = assignmentSubmissionsService.updateById(existingSubmission);
                if (updated) {
                    return Result.success("作业重新提交成功");
                } else {
                    return Result.error("作业重新提交失败");
                }
            }

            // 创建作业提交记录
            AssignmentSubmissions submission = new AssignmentSubmissions();
            submission.setAssignmentId(submissionDTO.getAssignmentId());
            submission.setStudentId(student.getId());
            submission.setContent(submissionDTO.getContent());
            submission.setAttachmentUrl(submissionDTO.getAttachmentUrl());
            submission.setSubmittedAt(LocalDateTime.now());
            // 状态设置为2(已提交)
            submission.setStatus(2);

            // 保存提交记录
            boolean saved = assignmentSubmissionsService.save(submission);
            if (saved) {
                return Result.success("作业提交成功");
            } else {
                return Result.error("作业提交失败");
            }
        } catch (Exception e) {
            return Result.error("作业提交异常: " + e.getMessage());
        }
    }

    /**
     * 获取作业提交记录
     *
     * @param assignmentId 作业ID
     * @return 作业提交记录
     */
    public Result<AssignmentSubmissions> getSubmissionByAssignmentId(Long assignmentId) {
        try {
            // 获取当前学生信息
            Students student = this.getUserByStudent().getData();
            if (student == null) {
                return Result.error("学生信息不存在");
            }

            // 查询作业提交记录
            QueryWrapper<AssignmentSubmissions> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("assignment_id", assignmentId);
            queryWrapper.eq("student_id", student.getId());

            AssignmentSubmissions submission = assignmentSubmissionsService.getOne(queryWrapper);
            return Result.success(submission);
        } catch (Exception e) {
            return Result.error("查询作业提交记录异常: " + e.getMessage());
        }
    }

    public void auroGenerateHomeworkRecords() {
        try {
            // 分批处理学生，每次处理100个

            List<Students> studentsBatch;
            List<Assignments> assignments = assignmentsService.lambdaQuery().eq(Assignments::getIsDue, true).list();
            //生成未完成作业记录
            assignments.forEach(assignment -> {
                List<Students> list = studentsService.lambdaQuery().eq(Students::getId, assignment.getClassId()).list();
                //班级学生id集合
                List<Long> collect = list.stream().map(Students::getId).collect(Collectors.toList());
                //已完成作业记录
                List<AssignmentSubmissions> assignmentSubmissions = assignmentSubmissionsService.lambdaQuery().eq(AssignmentSubmissions::getAssignmentId, assignment.getId()).list();
                //已完成作业记录id集合
                Set<Long> completeAssignmentSubmissions = assignmentSubmissions.stream().map(AssignmentSubmissions::getStudentId).collect(Collectors.toSet());
                // 筛选出没有提交作业的学生
                List<Long> incompleteStudents = collect.stream().filter(id -> !completeAssignmentSubmissions.contains(id)).collect(Collectors.toList());

                List<AssignmentSubmissions> collectRecords = incompleteStudents.stream().map(id -> {
                    AssignmentSubmissions submissions = new AssignmentSubmissions();
                    submissions.setAssignmentId(assignment.getId());
                    submissions.setStudentId(id);
                    submissions.setStatus(1);
                    return submissions;
                }).toList();

                if (!collectRecords.isEmpty()){
                    assignmentSubmissionsService.saveBatch(collectRecords);
                }
            });

        } catch (Exception e) {
            throw new RuntimeException("自动生成未完成记录失败: " + e.getMessage());
        }
    }
}
